//
//  test.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/6/16.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CYChart.h"
#import "CYTrendSource.h"

@interface CYChart()
@end
@implementation CYChart

+ (UIImage *)chartWithMissArray:(NSArray *)missArr winArr:(NSArray *)winArr index:(NSUInteger)index{
    if (missArr.count==0)
        return nil;
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//       UIImage *image = [self prepareDrawWithMissArr:missArr winArr:winArr index:index];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            complete(image);
//        });
//    });
    return [self prepareDrawWithMissArr:missArr winArr:winArr index:index];
}

/**
 * 1，missArr       是遗漏数组，
 * 2，winArr        是彩票开奖的信息，包括日期，时间，开奖号码
 * 3，row_count     行数
 * 4，column_coun   列数
 * 5，cell_width    每列的size = (width, height=width)  默认第一列是显示期数，size = (width, height=2*width)
 * 6，total_height  是整个excel的height
 */
+ (UIImage *)prepareDrawWithMissArr:(NSArray *)missArr winArr:(NSArray<CYWinModel *> *)winArr index:(NSUInteger)index{
    int column_count = (int)[[NSString arrayWithString:missArr[0]]count];//获取走势图的列数
    int row_count = (int)winArr.count;//走势图的行数
    CGFloat cell_width = SCREEN_WIDTH / (column_count + 2);//走势图每个单元的宽度
    CGFloat cell_height = 24;
    CGFloat total_height = (row_count + 1)* cell_height;//全部高度
    UIColor *cricle_color = (index%2)?BLUE_COLOR:THEME_COLOR;//走势图和选中的圆圈背景的颜色
    NSMutableArray *first_arr = [self firstLine:column_count];//第一行
    
    //获取上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_WIDTH, total_height), NO, 0.0);
    
    //==========================================================================================================================================================================================================//
    //画第一行背景
    [self drawFirstLineBackground:SCREEN_WIDTH heigth:cell_height];
    //画第一行的"期号"
    [self drawtext:@"期号" rect:CGRectMake(0, 0, cell_width * 2, cell_height) color:TEXT_BLACK_COLOR];
    
    //
    for (int i = 0; i < first_arr.count; i ++) {
        //画第一行竖线
        [self drawLineColor:[UIColor whiteColor] startPoint:CGPointMake( (2 + i) * cell_width, 0)
                   endPoint:CGPointMake((2 + i) * cell_width, cell_width)];
        //画除第一行以外的竖线
        [self drawLineColor:LINE_COLOR startPoint:CGPointMake( (2 + i) * cell_width, cell_width)
                   endPoint:CGPointMake((2 + i) * cell_width, total_height)];
        //画第一行数字
        CGRect rect = CGRectMake((2 + i) *cell_width, 0, cell_width, cell_height);
        [self drawNumber:first_arr[i] rect:rect isWin:NO isFirst:YES];
    }
    
    
    //==========================================================================================================================================================================================================//
    
    //画走势图连线
    UIBezierPath *line = [UIBezierPath bezierPath];/*画走势图连线*/
    line.lineWidth = 0.5;
    for (int i = 0; i < row_count; i ++) {//多少行
        
        //取出模型
        CYWinModel *winModel = winArr[i];
        NSString *date = [winModel.number substringFromIndex:winModel.number.length - 6];//中奖的期数
        date = [NSString stringWithFormat:@"%@期",date];//中奖的期数
        NSArray *winNumArr = [winModel.data componentsSeparatedByString:@","];//中奖号码的数组
        
        //画期数
        [self drawtext:date rect:CGRectMake(0, i * cell_height + cell_height, 2 * cell_width, cell_height) color:TEXT_GRAY_COLOR];
        
        //画横线
        [self drawLineColor:LINE_COLOR startPoint:CGPointMake(0, i * cell_height + cell_height)
                   endPoint:CGPointMake(SCREEN_WIDTH, i * cell_height + cell_height)];
        
        //从中奖号码数组，取出中奖号码的坐标 此坐标以1为起点,所以num_index - 1 = j 则说明是中奖号码，
        int num_index = [winNumArr[index] intValue];
        for (int j = 0; j < column_count; j++) {//多少列
            CGRect rect = CGRectMake((2 + j) *cell_width,i * cell_height + cell_height,  cell_width, cell_height);
            /*画走势图连接线*/
            if ((num_index  == j || (num_index == j && num_index == 0)) && i == 0)//起点
                [line moveToPoint:CGPointMake(rect.origin.x + cell_width / 2.0, rect.origin.y + cell_height / 2.0)];
            else if (num_index == j || (num_index == j && num_index == 0))//连接点
                [line addLineToPoint:CGPointMake(rect.origin.x + cell_width / 2.0, rect.origin.y + cell_height / 2.0)];
            if (num_index != j) //遗漏期数
                [self drawNumber:[missArr[i] componentsSeparatedByString:@","][j] rect:rect isWin:NO isFirst:NO];//未中奖号码
        }
    }
    [cricle_color set];//走势图连线颜色
    [line stroke];
    //==========================================================================================================================================================================================================//
    
    for (int i = 0; i < row_count; i ++) {
        
        //取出模型
        CYWinModel *winModel = winArr[i];
        NSArray *winNumArr = [winModel.data componentsSeparatedByString:@","];//中奖号码的数组
        int num_index = [winNumArr[index] intValue];//中奖号码
        
        for (int j = 0; j < column_count; j++) {//多少列
            CGRect rect = CGRectMake((2 + j) *cell_width,i * cell_height + cell_height,  cell_width, cell_height);
            if (num_index == j || (num_index == j && num_index == 0)){
                [self drawCircle:rect color:cricle_color radius:cell_height];//画出中奖号码背景
                [self drawNumber:[NSString arrayWithString:missArr[i]][j] rect:rect isWin:YES isFirst:NO];//中奖号码
            }
        }
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
        
    return  image;
    
}

//画线
+ (void)drawLineColor:(UIColor *)color startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint{
    
    UIBezierPath *path = [UIBezierPath  bezierPath];
    path.lineWidth = 0.5;
    [color set];
    [path moveToPoint:startPoint];
    [path addLineToPoint:endPoint];
    [path stroke];
    
}

//画号码
+ (void)drawNumber:(NSString *)text rect:(CGRect )rect isWin:(BOOL)isWin isFirst:(BOOL)isFirst{
    
    CGRect newRect = [self getTextRect:text inRect:rect];//算出文字画在矩形的中心，的左起点
    if (isFirst)//第一行号码的颜色
        [text drawInRect:newRect withAttributes: @{ NSFontAttributeName :[UIFont systemFontOfSize:13], NSForegroundColorAttributeName :TEXT_BLACK_COLOR }];
    else if (isWin)//中奖号码的颜色
        [text drawInRect:newRect withAttributes: @{ NSFontAttributeName :[UIFont systemFontOfSize:13], NSForegroundColorAttributeName :[UIColor whiteColor]}];
    else//未中奖号码的颜色
        [text drawInRect:newRect withAttributes: @{ NSFontAttributeName :[UIFont systemFontOfSize:13], NSForegroundColorAttributeName :TEXT_GRAY_COLOR}];
    
}

//画期数
+ (void)drawtext:(NSString *)text rect:(CGRect )rect color:(UIColor *)color {
    CGRect newRect = [self getTextRect:text inRect:rect];
    UIFont * font =(text.length > 5 )?[UIFont systemFontOfSize:AL(10)]:[UIFont systemFontOfSize:AL(13)];
    [text drawInRect:newRect withAttributes: @{ NSFontAttributeName :font, NSForegroundColorAttributeName :color } ];
}

//画圆圈
+ (void)drawCircle:(CGRect)rect color:(UIColor *)color radius:(CGFloat)radius{
    CGFloat select_circle_width = (SCREEN_WIDTH / (11 + 2) < radius - 3)?SCREEN_WIDTH / (11 + 2):radius - 3;//选中背景圆的宽度
    CGRect circle_rect = CGRectMake(rect.origin.x + (rect.size.width - select_circle_width) / 2.0, rect.origin.y + (rect.size.height - select_circle_width) / 2.0, select_circle_width, select_circle_width);
    UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:circle_rect];
    [color setFill]; /*填充颜色*/
    [circle fill];
    
}

//画第一行
+ (void)drawFirstLineBackground:(CGFloat) width heigth:(CGFloat)height{
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, width, height)];
    [RGBA(245, 246, 260, 1) setFill];
    [path fill];
    
}

/*根据彩票号码的个数，获取走势图第一行号码，第一行只起提示作用，不是开奖号码*/
+ (NSMutableArray *)firstLine:(int)count{
    NSMutableArray *subMutableArr = [NSMutableArray array];
    for (int i = 0; i < count; i ++) {
        [subMutableArr addObject:[NSString stringWithFormat:@"%d",i]];
    }
    return subMutableArr;
}

/*根据文字，算出size*/
+ (CGSize)gettextSzie:(NSString *)text{
    UIFont * font =(text.length > 5 )?[UIFont systemFontOfSize:AL(10)]:[UIFont systemFontOfSize:AL(13)];
    return  [text sizeWithAttributes:@{NSFontAttributeName :font}];
}

//文本在cell的中心区域
+ (CGRect )getTextRect:(NSString *)text inRect:(CGRect)rect{
    CGSize size = [self gettextSzie:text]; /*得到文字的size*/
    CGFloat width_gap = (rect.size.width - size.width) / 2.0;
    CGFloat height_gap = (rect.size.height - size.height) / 2.0;
    return CGRectMake(rect.origin.x + width_gap, rect.origin.y + height_gap, rect.size.width, rect.size.height); /*算出文字画在矩形的中心，的左起点*/
}

@end
